import { useEffect, useRef } from "react";
import {
    ArcRotateCamera, Color4, Engine, HemisphericLight, Mesh, MeshBuilder, Plane, Scene, StandardMaterial, Vector3, Color3, ShadowLight, SpotLight, Texture, UniversalCamera, FollowCamera,
} from '@babylonjs/core';


const canvas = document.createElement("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;


const engine = new Engine(canvas, true);
const scene = new Scene(engine);


const camera = new ArcRotateCamera('Camera', Math.PI / 3, Math.PI / 3, 9, new Vector3(0, 0, 0), scene);//第三人称
camera.attachControl(canvas, true);



const light = new HemisphericLight('pxg', new Vector3(1, 1, 0), scene);
const ground = MeshBuilder.CreateGround('ground', { width: 10, height: 10, updatable: true }, scene);
const updateAction: ((time: number) => {})[] = [];

scene.ambientColor = new Color3(1, 1, 1);
const mat = new StandardMaterial('myMat', scene);
mat.diffuseColor = new Color3(1, 1, 1);
mat.specularColor = new Color3(0, 0, 0);
mat.ambientColor = new Color3(1, 1, 1);
// mat.emissiveColor = new Color3(1, 1, 1);
// mat.alpha = 0.5;
mat.ambientTexture = new Texture('../image/image01.png', scene);

mat.wireframe = true;

const sphere = MeshBuilder.CreateSphere('sphere', { segments: 10, diameter: 3 }, scene);

sphere.position.set(0, 2, 0);
sphere.material = mat;



updateAction.push((time: number) => {

    // sphere.position.y = 2.5 + Math.sin(time / 200);

    return '';
});

// const light1 = new SpotLight('light1', new Vector3(0, 5, 0), new Vector3(0, -1, 0), Math.PI / 3, Math.PI / 2, scene);


const RenderStructure = () => {
    const divRef = useRef<HTMLDivElement>(null);
    useEffect(() => {
        const { current } = divRef;
        if (current != null) {
            current.innerHTML = '';
            current.append(canvas);
            ani(0);
        }
    }, []);
    return (
        <div ref={divRef}></div>
    );
};

export default RenderStructure;

function ani(time: number) {
    updateAction.forEach((action) => {
        action(time);
    })
    scene.render();

    requestAnimationFrame(ani);
}